<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas class='canvas' width="600" height="600"></canvas>
		<button>孙悟空</button>
		<button>猪八戒</button>
	  *合成图片效果较差
		<script>
			var canvas = document.querySelector('.canvas')
			var c1 = canvas.getContext('2d')
			canvas.style.border = '1px solid #000'
			
			var img = new Image()
			img.src= './img/img.png'
			
			var dirIndex = 0
			// drawImage(图片对象,裁剪位置x/y,裁剪的宽/高,x/y位置,图片宽/高)
			img.onload = function(){
				var frameIndex = 0
				setInterval(function(){
					c1.clearRect(0, 0, canvas.width, canvas.height)
					c1.drawImage(img, frameIndex * 200, dirIndex * 180, 200, 180, 200, 210, 200, 180)
					frameIndex++
					frameIndex %= 8 //4%4=0
				}, 1000/8)
			}
			
			var btn = document.querySelectorAll('button')
			btn[0].onclick = function(){
				dirIndex = 0
			}
			btn[1].onclick = function(){
				dirIndex = 1
			}
		</script>	
	</body>
</html>
